package com.celeritymq.utils;

import java.nio.ByteBuffer;

public class CelerityBuffer {
	private static final int HEAD_LENGTH = 4;
	private ByteBuffer headBuffer = ByteBuffer.allocate(HEAD_LENGTH);
	private boolean headReady = false;
	private boolean bodyReady = false;
	private int length = -1;
	private ByteBuffer buffer;
	private ByteBuffer inputBuffer;
	private ByteBuffer outputBuffer;

	public CelerityBuffer() {

	}

	private void allocateBodyBuffer() {
		int length = 0;
		headBuffer.rewind();
		for (int i = 0; i < HEAD_LENGTH; i++) {
			length = length + ((int) headBuffer.get() & 0xFF) << (24 - i * 8);
		}
		inputBuffer = ByteBuffer.allocate(length);
	}

	private void setLength(int length) {
		this.length = length;
	}

	public void readIn(ByteBuffer buffer) {

	}

	public ByteBuffer getHeadBuffer() {
		return headBuffer;
	}

	public void setHeadLength(ByteBuffer headBuffer) {
		this.headBuffer = headBuffer;

	}

//	public synchronized ByteBuffer getBuffer() {
//		if (bodyBuffer == null) {
//			return null;
//		}
//		if (buffer == null) {
//			headBuffer.limit();
//			byte[] array = new byte[headBuffer.limit() + bodyBuffer.limit()];
//			System.arraycopy(headBuffer.array(), 0, array, 0, headBuffer.limit());
//			System.arraycopy(bodyBuffer.array(), 0, array, headBuffer.limit(), bodyBuffer.limit());
//			buffer = ByteBuffer.wrap(array);
//		}
//
//		return buffer;
//	}

	public ByteBuffer getInputBuffer() {
		if(inputBuffer==null){
			allocateBodyBuffer();
		}
		return inputBuffer;
	}

	public void setInputBuffer(ByteBuffer inputBuffer) {
		this.inputBuffer = inputBuffer;
	}

	public ByteBuffer getOutputBuffer() {
		return outputBuffer;
	}

	public void setOutputBuffer(ByteBuffer outputBuffer) {
		this.outputBuffer = outputBuffer;
	}

	public void release() {
		headBuffer = null;
		inputBuffer = null;
		outputBuffer=null;
	}

}
